from rest_framework.viewsets import GenericViewSet
from rest_framework.filters import OrderingFilter
from django_filters import rest_framework as filters
from mixins import MyListModelMixin, MyDestroyModelMixin, MyCreateModelMixin, MyUpdateModelMixin
from pagination import MyPageNumberPagination
from response import APIResponse
from permission import MyPermissions
from status import *
from .filter import RoleProductFilter
from .serializers import RoleSerializers
from .models import Roles, RoleToMenu


class RoleViews(MyListModelMixin, MyDestroyModelMixin, MyCreateModelMixin, MyUpdateModelMixin, GenericViewSet):
    queryset = Roles.objects.filter(is_deleted=False).order_by("-orders").all()
    pagination_class = MyPageNumberPagination
    serializer_class = RoleSerializers
    permission_classes = [MyPermissions]
    filter_backends = [OrderingFilter, filters.DjangoFilterBackend]
    filterset_class = RoleProductFilter
    ordering_fields = ['id']
    filter_fields = ("name", "created_at", "updated_at")

    def perform_destroy(self, instance):
        if instance.id == 1:
            return APIResponse(code=ERROR, msg="超级管理员无法删除")
        instance.is_deleted = True
        instance.save()

    def perform_create(self, serializer):
        menu_ids = serializer.validated_data.pop('menu_ids')
        role = serializer.save()

        # 使用bulk_create 给角色批量增加菜单
        menu_list = [RoleToMenu(role=role, menu_id=menu_id) for menu_id in menu_ids]
        RoleToMenu.objects.bulk_create(menu_list)

    def perform_update(self, serializer):
        pk = eval(serializer.context["pk"])
        if pk == 1:
            return APIResponse(code=ERROR, msg="超级管理员不能修改")

        menu_ids = serializer.validated_data.pop('menu_ids')  # 获取菜单id
        RoleToMenu.objects.filter(role_id=pk).delete()
        menu_list = [RoleToMenu(role_id=pk, menu_id=menu_id) for menu_id in menu_ids]
        RoleToMenu.objects.bulk_create(menu_list)
        serializer.save()
